package service

import (
	"context"
	"goframe-zc/dto"
	"goframe-zc/internal/dao"
	"math"

	"github.com/gogf/gf/v2/util/gconv"
)

func GetOrderList(ctx context.Context, userId int, page, limit int) (*dto.OrderListRes2, error) {
	// 1. 查询订单主表（分页）
	var orders []*dto.Order
	orderListRes2 := &dto.OrderListRes2{}
	query := dao.ZcOrder.Ctx(ctx).
		Where("user_id = ?", userId).
		Order("id DESC")
	total, err := query.Count(&query)
	// 关联数据查询并映射到数据表里
	err = query.WithAll().Page(page, limit).Scan(&orders)
	if err != nil {
		return nil, err
	}
	if total == 0 {
		return orderListRes2, nil
	}
	// 查询出来结果映射到 对应下发的结构体里面
	var frontOrders []*dto.FrontOrder
	if err := gconv.Structs(orders, &frontOrders); err != nil {
		return nil, err
	}
	// 循环映射内部嵌套json数据
	for i, order := range orders {
		for _, goodsList := range order.GoodsList {
			goods := dto.FrontGoods{}
			if err := gconv.Structs(goodsList.Goods, &goods); err != nil {
				return nil, err
			}
			goods.GoodsNum = goodsList.GoodsNum
			// 添加到指定字段下面
			frontOrders[i].GoodsList = append(frontOrders[i].GoodsList, &goods)
		}
	}
	orderListRes2.List = frontOrders
	// 5. 计算总页数
	orderListRes2.Page = page
	orderListRes2.Limit = limit
	orderListRes2.Total = total
	orderListRes2.TotalPages = int(math.Ceil(float64(total) / float64(limit)))
	return orderListRes2, err
}
